package net.siufung.core.utils.spring;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;

import java.util.Objects;

/**
 * Spring的工具类
 * @author 陈建峰
 * @since 2022/2/9 11:10 下午
 */
public class SpringContextUtil implements ApplicationContextAware {
	
	@Nullable
	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	@Nullable
	public static ApplicationContext getContext(){
		return applicationContext;
	}
	
	@Nullable
	public static <T> T getBean(Class<T> clazz){
		if (Objects.isNull(applicationContext)) {
			return null;
		}
		return applicationContext.getBean(clazz);
	}

	@Nullable
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName){
		if (Objects.isNull(applicationContext)) {
			return null;
		}
		return (T) applicationContext.getBean(beanName);
	}

	@Nullable
	public static <T> T getBean(String beanName, Class<T> clazz) {
		if (Objects.isNull(applicationContext)) {
			return null;
		}
		return applicationContext.getBean(beanName, clazz);
	}

	@Nullable
	public static <T> ObjectProvider<T> getBeanProvider(Class<T> clazz) {
		if (Objects.isNull(applicationContext)) {
			return null;
		}
		return applicationContext.getBeanProvider(clazz);
	}

	@Nullable
	public static <T> ObjectProvider<T> getBeanProvider(ResolvableType resolvableType) {
		if (Objects.isNull(applicationContext)) {
			return null;
		}
		return applicationContext.getBeanProvider(resolvableType);
	}


}
